package com.zhao.dota.util;

import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;

@Slf4j
public class NioUtil {

    public static boolean upload(@NotNull String path, InputStream inputStream, long length) {
        int last = path.lastIndexOf("/");
        if (last > -1) {
            String substring = path.substring(0, last);
            File file = new File(substring);
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                if (!mkdirs) {
                    log.error("上传文件失败，目录[{}]创建失败，请检查权限", substring);
                    return false;
                }
            }
        }
        File file = new File(path + ".tmp");
        try (FileChannel outChannel = new FileOutputStream(file).getChannel();
             ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)){
            outChannel.transferFrom(readableByteChannel, 0, length);
        } catch (IOException e) {
            log.error(String.format("上传文件失败， path: [%s], length: [%d]", path, length), e);
            file.delete();
            return false;
        }
        file.renameTo(new File(path));
        return true;
    }

}
